//tab 切换
function setTab(name,cursel,n) {
  for (i = 1; i <= n; i++) {
    var menu=document.getElementById(name + "_" + i);
    menu.className=i==cursel?"item active":"item";
    var con = document.getElementById("con_" + name + "_" + i);
    con.style.display = i === cursel ? "block" : "none";
  }
}
//是否是预览显示模式 true = 预览模式 false = 编辑模式
var topoView;
//open js
// Reads files locally
function handleFiles(files)
{
  for (var i = 0; i < files.length; i++)
  {
    (function(file)
    {
      // Small hack to support import
      if (window.parent.openNew)
      {
        window.parent.open(window.parent.location.href);
      }

      var reader = new FileReader();
      reader.onload = function(e)
      {
        window.parent.openFile.setData(e.target.result, file.name);
      };
      reader.onerror = function(e)
      {
        console.log(e);
      };
      reader.readAsText(file);
    })(files[i]);
  }
};

// Handles form-submit by preparing to process response
function handleSubmit()
{
  var form = window.openForm || document.getElementById('openForm');

  // Checks for support of the File API for local file access
  // except for files where the parse is on the server
  if (window.parent.Graph.fileSupport && form.upfile.files.length > 0)
  {
    handleFiles(form.upfile.files);

    return false;
  }
  else
  {
    if (/(\.xml)$/i.test(form.upfile.value) || /(\.txt)$/i.test(form.upfile.value) ||
      /(\.mxe)$/i.test(form.upfile.value))
    {
      // Small hack to support import
      if (window.parent.openNew)
      {
        window.parent.open(window.parent.location.href);
      }
      // NOTE: File is loaded via JS injection into the iframe, which in turn sets the
      // file contents in the parent window. The new window asks its opener if any file
      // contents are available or waits for the contents to become available.
      return true;
    }
    else
    {
      window.parent.mxUtils.alert(window.parent.mxResources.get('invalidOrMissingFile'));

      return false;
    }
  }
};
// Hides this dialog
function hideWindow(cancel)
{
  window.parent.openFile.cancel(cancel);
}
function fileChanged()
{
  var form = window.openForm || document.getElementById('openForm');
  var openButton = document.getElementById('openButton');
  if (form.upfile.value.length > 0)
  {
    openButton.removeAttribute('disabled');
  }
  else
  {
    openButton.setAttribute('disabled', 'disabled');
  }
}

function main(){
  if (window.parent.Editor.useLocalStorage)
  {
    document.body.innerHTML = '';
    var div = document.createElement('div');
    div.style.fontFamily = 'Arial';

    if (localStorage.length == 0)
    {
      window.parent.mxUtils.write(div, window.parent.mxResources.get('noFiles'));
    }
    else
    {
      var keys = [];

      for (var i = 0; i < localStorage.length; i++)
      {
        keys.push(localStorage.key(i));
      }

      // Sorts the array by filename (key)
      keys.sort(function (a, b)
      {
        return a.toLowerCase().localeCompare(b.toLowerCase());
      });

      for (var i = 0; i < keys.length; i++)
      {
        var link = document.createElement('a');
        link.style.fontDecoration = 'none';
        link.style.fontSize = '14pt';
        var key = keys[i];
        window.parent.mxUtils.write(link, key);
        link.setAttribute('href', 'javascript:void(0);');
        div.appendChild(link);

        var img = document.createElement('span');
        img.className = 'geSprite geSprite-delete';
        img.style.position = 'relative';
        img.style.cursor = 'pointer';
        img.style.display = 'inline-block';
        div.appendChild(img);

        window.parent.mxUtils.br(div);

        window.parent.mxEvent.addListener(img, 'click', (function(k)
        {
          return function()
          {
            if (window.parent.mxUtils.confirm(window.parent.mxResources.get('delete') + ' "' + k + '"?'))
            {
              localStorage.removeItem(k);
              window.location.reload();
            }
          };
        })(key));

        window.parent.mxEvent.addListener(link, 'click', (function(k)
        {
          return function()
          {
            try
            {
              window.parent.open(window.parent.location.href);
              window.parent.openFile.setData(localStorage.getItem(k), k);
            }
            catch (e)
            {
              window.parent.mxUtils.alert(e.message);
            }
          };
        })(key));
      }
    }

    window.parent.mxUtils.br(div);
    window.parent.mxUtils.br(div);

    var cancelBtn = window.parent.mxUtils.button(window.parent.mxResources.get('cancel'), function()
    {
      hideWindow(true);
    });
    cancelBtn.className = 'geBtn';
    div.appendChild(cancelBtn);

    document.body.appendChild(div);
  }
  else
  {
    var editLink = document.getElementById('editLink');
    var openButton = document.getElementById('openButton');
    openButton.value = window.parent.mxResources.get(window.parent.openKey || 'open');
    var cancelButton = document.getElementById('cancelButton');
    cancelButton.value = window.parent.mxResources.get('cancel');
    var supportedText = document.getElementById('openSupported');
    supportedText.innerHTML = window.parent.mxResources.get('openSupported');
    var form = window.openForm || document.getElementById('openForm');

    form.setAttribute('action', window.parent.OPEN_URL);
  }
};

//open js


//创建签名
function createSign(params,timestamp){
  var data = JSON.parse(params);
  data.token = token;
  data.timestamp = timestamp;
  const signParams = sort_ASCII(data);
  return hex_md5(signParams + 'signKey=' + signKey);
}

//ascii排序
function sort_ASCII(obj){
  var arr = new Array()
  var num = 0
  for (var i in obj) {
    arr[num] = i
    num++
  }
  var sortArr = arr.sort()
  var sortObj = {}
  for (var j in sortArr) {
    sortObj[sortArr[j]] = obj[sortArr[j]]
  }
  // sortObj 是排序后生成的新的对象参数  取出所有 key 和 value 拼接成 key=value&key=value& 的形式
  //  sortObj[key_] 是根据key 取value 的值
  var result = ''
  Object.keys(sortObj).forEach(key_ => {
    if (sortObj[key_] !== '' && sortObj[key_] !== null && sortObj[key_] !== undefined) {
      if (Array.isArray(sortObj[key_])) {
        result += key_ + '=[' + sortObj[key_].toString() + ']&'
      } else {
        result += key_ + '=' + sortObj[key_] + '&'
      }
    }
  })
  return result
}
//取参数方法beg
// Parses URL parameters. Supported parameters are:
// - lang=xy: Specifies the language of the user interface.
// - touch=1: Enables a touch-style user interface.
// - chrome=0: Chromeless mode.
// Default resources are included in grapheditor resources
var urlParams = (function(url){
  var result = new Object();
  var idx = url.lastIndexOf('?');
  if (idx > 0){
    var params = url.substring(idx + 1).split('&');
    for (var i = 0; i < params.length; i++){
      idx = params[i].indexOf('=');
      if (idx > 0){
        result[params[i].substring(0, idx)] = params[i].substring(idx + 1);
      }
    }
  }
  return result;
})(window.location.href);
mxLoadResources = false;
//取参数方法end
// 移出报警
function delOverlay (graph,id){
  // 获取ID单元
  var cell = graph.getModel().getCell(id);
  // 修改有报警物体的样式
  graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, "#CCCCCC", [cell]);
  graph.setCellStyles(mxConstants.STYLE_FONTCOLOR, "#000000", [cell]);
  // 移除告警
  graph.removeCellOverlays(cell);
}

// 给物体添加报警
function addOverlay(graph,id, state){
  // 获取ID单元
  var cell = graph.getModel().getCell(id);
  // 修改有报警物体的样式
  graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, "#FF0000", [cell]);
  graph.setCellStyles(mxConstants.STYLE_FONTCOLOR, "#FFFFFF", [cell]);
  // 添加告警
  graph.addCellOverlay(cell, createOverlay(graph.warningImage, state));
}

// 创建告警信息
function createOverlay(image, tooltip){
  //function mxCellOverlay(image,tooltip,align,verticalAlign,offset,cursor)
  //image图片，tooltip提示，align位置，verticalAlign竖直位置
  var overlay = new mxCellOverlay(image, tooltip);
  overlay.addListener(mxEvent.CLICK, function(sender, evt){
    mxUtils.alert(tooltip);
  });
  return overlay;
}
